<template>
  <div style="padding:10px">
    <el-table
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column
        prop="workOrderNo"
        label="ID"
      />
      <el-table-column
        prop="name"
        label="姓名"
      />
      <el-table-column
        prop="serviceStartTime"
        label="时间"
      />
      <el-table-column
        prop="address"
        label="地址"
      />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <div>
            <el-button
              type="text"
              @click="send(scope.row)"
            >派单</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="dialogVisible"
      width="80%"
    >
      <div>
        <div class="tableTop1">
          <div class="top1Left">员工排班表</div>
          <div class="top1Right">
            <div class="day">
              <div
                style="cursor:pointer;margin-right:8px;"
                @click="dayPrev"
              >
                <i class="el-icon-arrow-left" />
              </div>
              <div class="weekdate">
                {{ `${moment(serviceStartTime).format("YYYY年MM月DD日")}` }}
              </div>
              <div
                style="cursor:pointer;margin-left:8px;"
                @click="dayNext"
              >
                <i class="el-icon-arrow-right" />
              </div>
            </div>
            <div
              style="cursor: pointer;color: #ff7f4c;margin-left:8px;"
              @click="goBackCurrent"
            >
              回到今日
            </div>
          </div>
        </div>
        <div class="tableTop2">
          <span>用户期望服务时间: {{ serviceStartTime }}</span>
          <span>服务需要时长: {{ Math.ceil(serviceTotalTime).toFixed(2) }}小时</span>
          <span>服务人数:1</span>
        </div>
        <div class="tableTop3">
          <div style="display:flex;align-items: center;position:relative;">
            <div
              class="staffName"
              style="width:100px;"
            >员工名称:</div>
            <el-input
              v-model="searchStaffName"
              placeholder="搜索员工"
            />
            <i
              class="el-icon-search"
              @click="searchPeople"
            />
          </div>
          <div style="display:flex;align-items:center;">
            <div style="width:20px;height:20px;border: 1px solid #e5e5e5;border-radius:12px;margin-right:10px;background-color: #edf2fc;" />
            <div style="margin-right:10px;">不可约</div>
            <div style="width: 20px;height: 20px;border: 1px solid #E9E9E9;border-radius:50%;margin-right:5px;background-color: #ff8043;">
              <i
                class="el-icon-check"
                style="margin-left:3px;margin-top: 4px;"
              />
            </div>
            <div style="margin-right:10px;">已约</div>
            <div style="width:20px;height:20px;border: 1px solid #B1B1B1;border-radius:12px;margin-right:10px;" />
            <div>可约</div>
          </div>
        </div>
        <div
          v-loading="lens !== '' ? false : true"
          class="tables"
        >
          <el-table
            v-if="list.staffWorkTimeVos == [] ? '暂无数据' : list"
            id="tableId"
            ref="table"
            :data="list"
            border
            highlight-current-row
            @current-change="handleCurrentChangeDay"
          >
            <el-table-column
              v-if="list.length > 0"
              prop="staffName"
              label="姓名/时间"
              width="80"
            >
              <template slot-scope="scope">
                {{ scope.row.staffName }}
              </template>
            </el-table-column>
            <el-table-column
              v-for="(item, index) in listtimes"
              :key="index"
              prop="staffCode"
              :label="item.time"
              width="60"
              class="fist"
            >
              <template slot-scope="scope">
                <!-- 已约 -->
                <div v-if="scope.row.times[index].status == 1">
                  <el-checkbox
                    checked
                    disabled
                    class="one"
                  />
                </div>
                <!-- 不可约（包含请假和休息日） -->
                <div v-if="
                    scope.row.times[index].status == 3 ||
                      scope.row.times[index].status == 2
                  ">
                  <el-checkbox
                    disabled
                    class="two"
                  />
                </div>
                <!-- 可约 -->
                <div v-if="scope.row.times[index].status == 4">
                  <el-checkbox
                    v-model="scope.row.times[index].checked"
                    class="three"
                    @change="
                      reducible(
                        scope.row.times[index],
                        $event,
                        scope.row.times[index].time,
                        scope.row.staffCode
                      )
                    "
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 派单 -->
    <el-dialog
      :visible.sync="centerDialogVisibles"
      width="30%"
      center
      :modal="false"
      @close="sandersDialog"
    >
      <span>当前选择时段:{{ fisttims }}</span>
      <div style="margin-top:10px;">
        <span style="margin-right:40px;">服务人数:1</span>
        <span>服务总时长:{{ Math.ceil(serviceTotalTime).toFixed(2) }}小时</span>
      </div>
      <p style="margin-top:10px;">是否确认派单？</p>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="sanders">重新选择</el-button>
        <el-button
          style="background-color:#fd804c;color: #fff;"
          @click="sander"
        >立即派单</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  data() {
    return {
      tableData: [{
        name: '王小虎',
        orderItemType: '1',
        workOrderNo: '1111111',
        serviceStartTime: '2021-11-16 08:00:00',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        name: '王小虎',
        orderItemType: '0',
        workOrderNo: '222222',
        serviceStartTime: '2021-11-17 09:00:00',
        address: '上海市普陀区金沙江路 1517 弄'
      }],
      nums: [],
      list: [],
      value: [],
      states: [],
      lens: '',
      startTime: '',
      endTime: '',
      fisttims: '',
      listtimes: '',
      searchStaffName: '',
      serviceStartTime: '',
      serviceTotalTime: '',
      workOrderNos: '',
      centerDialogVisibles: false,
      dialogVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    send(e) {
      this.dialogVisible = true
      this.workOrderNos = e.workOrderNo
      this.serviceStartTime = e.serviceStartTime
    },
    // json
    getList() {
      const res = require('../json/paidan.json')
      this.lens = res.data.staffWorkTimeVos.length
      if (this.lens > 0) {
        this.list = res.data.staffWorkTimeVos
        this.serviceTotalTime = (
          res.data.simpleWordOrder.serviceTotalTime / 60
        ).toFixed(2)
        res.data.staffWorkTimeVos.forEach(e => {
          e.times.forEach(k => {
            k.checked === true
          })
          this.listtimes = e.times
        })
      } else {
        this.$message.error('没有可派单的阿姨!')
      }
    },
    // 重新选择
    sanders() {
      this.centerDialogVisibles = false
      this.states.forEach(e => (e.checked = false))
      this.value = []
      this.states = []
      this.nums = []
    },
    // 关闭弹框的事件
    sandersDialog() {
      this.centerDialogVisibles = false
      this.states.forEach(e => (e.checked = false))
      this.value = []
      this.states = []
      this.nums = []
    },
    // 立即派单
    sander() {
      this.$message({
        message: '派单成功',
        type: 'success'
      })
      this.dialogVisible = false
      this.centerDialogVisibles = false
    },
    // 可约
    reducible(j, s, time, e) {
      this.states.push(j)
      if (s) {
        this.nums.push(time)
      } else {
        this.nums.splice(this.nums.indexOf(time), 1)
      }

      // 时间选择不能有间隔
      const arr = this.nums
      const dates = Array.from(new Set(arr))
      const arraySort = this.arrSort(dates)
      for (let i = 0; i < arraySort.length; i++) {
        if (i > 0) {
          const beforeDate = new Date(
            '2021',
            '09',
            '30',
            arraySort[i - 1].split(':')[0],
            arraySort[i - 1].split(':')[1],
            '00'
          )
          const afterDate = new Date(
            '2021',
            '09',
            '30',
            arraySort[i].split(':')[0],
            arraySort[i].split(':')[1],
            '00'
          )
          const min = beforeDate.getMinutes()
          beforeDate.setMinutes(min + 30)
          if (beforeDate.getTime() != afterDate.getTime()) {
            this.$message.error('时间选择不能有间隔!')
            this.states.forEach(e => (e.checked = false))
            this.value = []
            this.states = []
            this.nums = []
          }
        }
      }

      // 派单传值
      const el = this.nums[this.nums.length - 1] // 最后
      const ell = this.nums[0] // 最新
      const day = moment(this.expectDeliveryTime).format('YYYY-MM-DD')
      this.startTime = `${day} ${ell}:00`
      this.endTime = `${day} ${el}:00`
      this.fisttims = `${day} ${ell} ~ ${el}`
      this.staffCodes = e

      // 派单弹框
      if (this.serviceTotalTime == 0.00) {
        this.$message.error('没有可派单的阿姨!')
        this.states.forEach(e => (e.checked = false))
        this.states = []
        this.nums = []
      } else {
        if (
          Array.from(new Set(this.nums)).length ===
          Math.ceil(this.serviceTotalTime) * 2 + 1
        ) {
          this.centerDialogVisibles = true
        }
      }
      // 阿姨code不能重复
      this.value.push(e)
      const a = this.value[0] // 最新
      const all = this.value[this.value.length - 1] // 最后
      if (a !== all) {
        this.$message.error('错了哦，请选择一位阿姨')
        this.states.forEach(e => (e.checked = false))
        this.value = []
        this.states = []
      }
    },
    arrSort(arr) {
      const len = arr.length
      for (let i = 0; i < len - 1; i++) {
        for (let j = 0; j < len - 1 - i; j++) {
          const beforeDate = new Date('2021', '09', '30', arr[j].split(':')[0], arr[j].split(':')[1], '00')
          const afterDate = new Date('2021', '09', '30', arr[j + 1].split(':')[0], arr[j + 1].split(':')[1], '00')
          if (beforeDate.getTime() > afterDate.getTime()) {
            const temp = arr[j]
            arr[j] = arr[j + 1]
            arr[j + 1] = temp
          }
        }
      }
      return arr
    },
    // 搜索员工
    setCurrent(row) {
      this.$refs.table.setCurrentRow(row)
    },
    handleCurrentChangeDay(value) {
      this.currentRowDay = value
    },
    searchPeople() {
      if (this.searchStaffName === '') {
        this.$message.error('请输入员工姓名')
        return false
      }
      const refTab = this.$refs.table
      const refdata = refTab.data
      // //console.log(refTab)
      for (let i = 0; i < refdata.length; i++) {
        if (refdata[i].hasOwnProperty('staffName')) {
          var tableIdLocation = refdata
            .map(item => item.staffName)
            .indexOf(this.searchStaffName)
        }
      }
      if (tableIdLocation == -1) {
        this.$message.error('查询不到此员工')
        return false
      }
      this.setCurrent(refdata[tableIdLocation])
      const myTableId = document.getElementById('tableId').childNodes
      const myTableIdChildNo3 = myTableId[2].childNodes
      const myTableIdChildNo3ChildNo1 = myTableIdChildNo3[0].childNodes
      const tbobyChildNo2 = myTableIdChildNo3ChildNo1[1]
      const kk = tbobyChildNo2.childNodes
      const kkll = kk[tableIdLocation]
      kkll.setAttribute('id', 'table_td_bg')
      const element = document.getElementById('table_td_bg')
      element.scrollIntoView({ block: 'center' })
    },
    // 回到今日
    goBackCurrent() {
      this.list = []
      const data = moment(new Date()).format('YYYY-MM-DD') // 当前日期
      this.serviceStartTime = data
      this.getList()
    },
    // 减一天
    dayPrev() {
      this.list = []
      const dayPrev = moment(new Date(this.serviceStartTime))
        .subtract(1, 'days')
        .format('YYYY-MM-DD')
      this.serviceStartTime = dayPrev
      this.getList()
    },
    // 加一天
    dayNext() {
      this.list = []
      const dayNext = moment(new Date(this.serviceStartTime))
        .add(1, 'days')
        .format('YYYY-MM-DD')
      this.serviceStartTime = dayNext
      this.getList()
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-dialog__header {
  padding: 0px;
}
::v-deep .el-dialog__body {
  padding-top: 22px;
}
.tableTop1 {
  display: flex;
  justify-content: space-between;
  padding-right: 40px;
  .day {
    display: flex;
  }
  .top1Right {
    display: flex;
  }
}
.tableTop2 {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
  padding: 0 32px 0 32px;
  height: 45px;
  line-height: 45px;
}
.tableTop3 {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
.tables {
  margin-top: 10px;
  ::v-deep .el-table__row {
    cursor: pointer;
    line-height: 0px;
    font-size: 12px;
    font-weight: 400;
  }
}
::v-deep .el-icon-check:before {
  color: #fff;
}
::v-deep .el-checkbox__inner {
  width: 20px;
  height: 20px;
  border-radius: 10px;
}
::v-deep .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
  top: 3px;
  left: 6px;
  width: 5px;
  height: 8px;
  border-color: #fff;
}
.one {
  ::v-deep .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color: #ff8043;
    border-radius: 10px;
  }
}
.three {
  ::v-deep .el-checkbox__input.is-focus .el-checkbox__inner {
    border-color: #b1b1b1;
  }
  ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #fff;
    border: 1px solid #b1b1b1;
  }
  ::v-deep .el-checkbox__inner::after {
    top: 3px;
    left: 6px;
    width: 5px;
    height: 8px;
    border-color: #b1b1b1;
  }
}
.el-icon-search {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}
::v-deep .has-gutter {
  font-size: 13px;
}
</style>
